#include "file.h"

extern config_info_t configInfo;
extern int linkAllProcess;

String wifi_info = "/wifi_info.txt"; // 被读取的文件位置和名称

void setup_file(void)
{
  uint8_t tmpBuff[256];
  File newFile;

  DEBUG_LOG_println("");
  if (LittleFS.begin())
  {
    DEBUG_LOG_println("LittleFS Started.");
  }
  else
  {
    DEBUG_LOG_println("LittleFS Failed to Start.");
    DEBUG_LOG_println("LittleFS format start");
    LittleFS.format(); // 格式化SPIFFS(清除闪存文件系统)
    if (LittleFS.begin())
    {
      DEBUG_LOG_println("LittleFS Started.");
    }
    else
    {
      DEBUG_LOG_println("LittleFS Failed to Start again.");
    }
  }

  newFile = LittleFS.open(wifi_info, "r");
  if (!newFile) // 判断闪存文件/etc/wifi_info.txt是否存在
  {
    DEBUG_LOG_print(wifi_info);
    DEBUG_LOG_println(" not found.");
  }
  else
  {
    DEBUG_LOG_print(wifi_info);
    DEBUG_LOG_println(" was found.");
    newFile.read(tmpBuff, newFile.size());
    file_ReadWiFiConfig(String((char *)tmpBuff)); //读取文件的wifi配置信息和MQTT服务器和用户密码
    newFile.close();
    WiFi.begin(configInfo.sta_ssid, configInfo.sta_passwd);  //根据读取的信息，自动连接wifi
    linkAllProcess = 1;
  }

  // 可用空间总和（单位：字节）
  DEBUG_LOG_print("totalBytes: ");
  DEBUG_LOG_print(LittleFS.totalBytes());
  DEBUG_LOG_println(" Bytes");

  // 已用空间（单位：字节）
  DEBUG_LOG_print("usedBytes: ");
  DEBUG_LOG_print(LittleFS.usedBytes());
  DEBUG_LOG_println(" Bytes");

  DEBUG_LOG_println("");
}

void file_ReadWiFiConfig(String buff)
{
  uint16_t i;
	uint16_t start = 0;
	uint16_t segment = 0;
  String param[6];

  for(i = 0; i < 6; i++)
  {
    start = buff.indexOf('\"', segment + 1) + 1;
    segment = buff.indexOf('\"', start);
    param[i] = buff.substring(start, segment);
  }

  configInfo.sta_ssid = param[0];
  configInfo.sta_passwd = param[1];
  configInfo.mqtt_addr = param[2];
  configInfo.mqtt_port = param[3];
  configInfo.mqtt_user = param[4];
  configInfo.mqtt_passwd = param[5];

  DEBUG_LOG_println("====== wifi_info.txt ======");
  DEBUG_LOG_print("sta_ssid:");
  DEBUG_LOG_println(configInfo.sta_ssid + String("#"));
  // DEBUG_LOG_print("sta_passwd:");
  // DEBUG_LOG_println(configInfo.sta_passwd + String("#"));
  // DEBUG_LOG_print("mqtt_addr:");
  // DEBUG_LOG_println(configInfo.mqtt_addr + String("#"));
  // DEBUG_LOG_print("mqtt_port:");
  // DEBUG_LOG_println(configInfo.mqtt_port + String("#"));
  DEBUG_LOG_print("mqtt_user:");
  DEBUG_LOG_println(configInfo.mqtt_user + String("#"));
  // DEBUG_LOG_print("mqtt_passwd:");
  // DEBUG_LOG_println(configInfo.mqtt_passwd + String("#"));
  DEBUG_LOG_println("");
}

